package com.ias.business.testbiz.controller;

import com.ias.business.testbiz.entity.TestBizEntity;
import com.ias.business.testbiz.service.TestBizMapperDemoService;
import com.ias.common.result.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * TestBizMapper功能测试控制器
 * 提供REST API接口演示Mapper.xml中定义的各种功能
 * 
 * @author IAS Team
 * @since 1.0.0
 */
@Slf4j
@RestController
@RequestMapping("/test/mapper")
@RequiredArgsConstructor
@Tag(name = "TestBizMapper测试", description = "演示MyBatis Mapper.xml各种功能的测试接口")
public class TestBizMapperController {

    private final TestBizMapperDemoService testBizMapperDemoService;

    @GetMapping("/basic-query/{bizCode}")
    @Operation(summary = "基础查询测试", description = "根据业务编码查询单个记录")
    public Result<TestBizEntity> testBasicQuery(
            @Parameter(description = "业务编码") @PathVariable String bizCode) {
        log.info("测试基础查询功能，业务编码：{}", bizCode);
        
        TestBizEntity result = testBizMapperDemoService.demonstrateBasicQuery(bizCode);
        
        if (result != null) {
            return Result.success("查询成功", result);
        } else {
            return Result.failed("未找到对应的业务记录");
        }
    }

    @PostMapping("/batch-operations")
    @Operation(summary = "批量操作测试", description = "演示批量插入和查询功能")
    public Result<Map<String, Object>> testBatchOperations() {
        log.info("测试批量操作功能");
        
        // 准备测试数据
        List<TestBizEntity> entities = createTestEntities();
        
        Map<String, Object> result = testBizMapperDemoService.demonstrateBatchOperations(entities);
        
        if ((Boolean) result.get("success")) {
            return Result.success("批量操作测试成功", result);
        } else {
            return Result.failed(result.get("message").toString());
        }
    }

    @GetMapping("/conditional-query")
    @Operation(summary = "条件查询测试", description = "演示多种条件查询功能")
    public Result<Map<String, Object>> testConditionalQuery(
            @Parameter(description = "搜索关键词") @RequestParam(required = false) String keyword,
            @Parameter(description = "业务类型") @RequestParam(required = false) Integer bizType,
            @Parameter(description = "状态") @RequestParam(required = false) Integer status) {
        log.info("测试条件查询功能，关键词：{}，业务类型：{}，状态：{}", keyword, bizType, status);
        
        Map<String, Object> result = testBizMapperDemoService.demonstrateConditionalQuery(keyword, bizType, status);
        
        return Result.success("条件查询测试完成", result);
    }

    @GetMapping("/statistics")
    @Operation(summary = "统计分析测试", description = "演示各种统计分析功能")
    public Result<Map<String, Object>> testStatistics(
            @Parameter(description = "业务类型（可选）") @RequestParam(required = false) Integer bizType) {
        log.info("测试统计分析功能，业务类型：{}", bizType);
        
        Map<String, Object> result = testBizMapperDemoService.demonstrateStatisticsAnalysis(bizType);
        
        return Result.success("统计分析测试完成", result);
    }

    @GetMapping("/time-range-query")
    @Operation(summary = "时间范围查询测试", description = "根据时间范围查询记录")
    public Result<List<TestBizEntity>> testTimeRangeQuery(
            @Parameter(description = "开始时间") 
            @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @Parameter(description = "结束时间") 
            @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        log.info("测试时间范围查询，开始时间：{}，结束时间：{}", startTime, endTime);
        
        // 如果没有传入时间参数，使用默认值
        if (startTime == null) {
            startTime = LocalDateTime.now().minusDays(7); // 最近7天
        }
        if (endTime == null) {
            endTime = LocalDateTime.now();
        }
        
        List<TestBizEntity> result = testBizMapperDemoService.demonstrateTimeRangeQuery(startTime, endTime);
        
        return Result.success(String.format("时间范围查询完成，找到%d条记录", result.size()), result);
    }

    @PostMapping("/dynamic-sql")
    @Operation(summary = "动态SQL测试", description = "演示动态SQL查询功能")
    public Result<List<TestBizEntity>> testDynamicSQL(@RequestBody TestBizEntity queryEntity) {
        log.info("测试动态SQL功能，查询条件：{}", queryEntity);
        
        List<TestBizEntity> result = testBizMapperDemoService.demonstrateDynamicSQL(queryEntity);
        
        return Result.success(String.format("动态SQL查询完成，找到%d条记录", result.size()), result);
    }

    @GetMapping("/pagination")
    @Operation(summary = "分页查询测试", description = "演示自定义分页查询功能")
    public Result<Map<String, Object>> testPagination(
            @Parameter(description = "搜索关键词") @RequestParam(required = false) String keyword,
            @Parameter(description = "业务类型") @RequestParam(required = false) Integer bizType,
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") int pageNum,
            @Parameter(description = "页大小", example = "10") @RequestParam(defaultValue = "10") int pageSize) {
        log.info("测试分页查询功能，关键词：{}，业务类型：{}，页码：{}，页大小：{}", keyword, bizType, pageNum, pageSize);
        
        Map<String, Object> result = testBizMapperDemoService.demonstratePagination(keyword, bizType, pageNum, pageSize);
        
        return Result.success("分页查询测试完成", result);
    }

    @GetMapping("/uniqueness-check")
    @Operation(summary = "唯一性检查测试", description = "测试业务编码唯一性检查功能")
    public Result<Boolean> testUniquenessCheck(
            @Parameter(description = "业务编码") @RequestParam String bizCode,
            @Parameter(description = "排除的ID") @RequestParam(required = false) Long excludeId) {
        log.info("测试唯一性检查功能，业务编码：{}，排除ID：{}", bizCode, excludeId);
        
        boolean canUse = testBizMapperDemoService.demonstrateUniquenessCheck(bizCode, excludeId);
        
        String message = canUse ? "业务编码可以使用" : "业务编码已存在";
        return Result.success(message, canUse);
    }

    @PostMapping("/batch-status-update")
    @Operation(summary = "批量状态更新测试", description = "批量更新记录状态")
    public Result<Map<String, Object>> testBatchStatusUpdate(
            @Parameter(description = "ID列表") @RequestParam List<Long> ids,
            @Parameter(description = "新状态") @RequestParam Integer status) {
        log.info("测试批量状态更新功能，ID列表：{}，新状态：{}", ids, status);
        
        Map<String, Object> result = testBizMapperDemoService.demonstrateBatchStatusUpdate(ids, status);
        
        if ((Boolean) result.get("success")) {
            return Result.success("批量状态更新测试成功", result);
        } else {
            return Result.failed(result.get("message").toString());
        }
    }

    @PostMapping("/soft-delete")
    @Operation(summary = "软删除测试", description = "批量软删除记录")
    public Result<Map<String, Object>> testSoftDelete(
            @Parameter(description = "ID列表") @RequestParam List<Long> ids) {
        log.info("测试软删除功能，ID列表：{}", ids);
        
        Map<String, Object> result = testBizMapperDemoService.demonstrateSoftDelete(ids);
        
        if ((Boolean) result.get("success")) {
            return Result.success("软删除测试成功", result);
        } else {
            return Result.failed(result.get("message").toString());
        }
    }

    @PostMapping("/init-test-data")
    @Operation(summary = "初始化测试数据", description = "创建一些测试数据用于演示")
    public Result<Map<String, Object>> initTestData() {
        log.info("初始化测试数据");
        
        List<TestBizEntity> entities = createTestEntities();
        
        // 添加更多样化的测试数据
        entities.addAll(createMoreTestEntities());
        
        Map<String, Object> result = testBizMapperDemoService.demonstrateBatchOperations(entities);
        
        if ((Boolean) result.get("success")) {
            return Result.success("测试数据初始化成功", result);
        } else {
            return Result.failed(result.get("message").toString());
        }
    }

    @GetMapping("/demo-all")
    @Operation(summary = "完整功能演示", description = "演示所有Mapper.xml功能的综合测试")
    public Result<Map<String, Object>> demoAllFeatures() {
        log.info("开始完整功能演示");
        
        Map<String, Object> demoResult = new java.util.HashMap<>();
        
        try {
            // 1. 初始化测试数据
            List<TestBizEntity> testData = createTestEntities();
            testData.addAll(createMoreTestEntities());
            Map<String, Object> batchResult = testBizMapperDemoService.demonstrateBatchOperations(testData);
            demoResult.put("1_批量插入", batchResult);
            
            // 2. 基础查询演示
            TestBizEntity basicQuery = testBizMapperDemoService.demonstrateBasicQuery("DEMO_ORDER_001");
            demoResult.put("2_基础查询", basicQuery);
            
            // 3. 条件查询演示
            Map<String, Object> conditionalQuery = testBizMapperDemoService.demonstrateConditionalQuery("管理", 1, null);
            demoResult.put("3_条件查询", conditionalQuery);
            
            // 4. 统计分析演示
            Map<String, Object> statistics = testBizMapperDemoService.demonstrateStatisticsAnalysis(null);
            demoResult.put("4_统计分析", statistics);
            
            // 5. 时间范围查询演示
            LocalDateTime startTime = LocalDateTime.now().minusHours(1);
            LocalDateTime endTime = LocalDateTime.now().plusHours(1);
            List<TestBizEntity> timeRangeQuery = testBizMapperDemoService.demonstrateTimeRangeQuery(startTime, endTime);
            demoResult.put("5_时间范围查询", Map.of("count", timeRangeQuery.size(), "data", timeRangeQuery.stream().limit(3).toArray()));
            
            // 6. 分页查询演示
            Map<String, Object> pagination = testBizMapperDemoService.demonstratePagination("DEMO", null, 1, 5);
            demoResult.put("6_分页查询", pagination);
            
            // 7. 唯一性检查演示
            boolean uniquenessCheck = testBizMapperDemoService.demonstrateUniquenessCheck("DEMO_ORDER_001", null);
            demoResult.put("7_唯一性检查", Map.of("bizCode", "DEMO_ORDER_001", "exists", !uniquenessCheck));
            
            demoResult.put("演示状态", "所有功能演示完成");
            
            return Result.success("完整功能演示成功", demoResult);
            
        } catch (Exception e) {
            log.error("功能演示过程中出现异常", e);
            demoResult.put("演示状态", "演示过程中出现异常：" + e.getMessage());
            return Result.failed("功能演示失败");
        }
    }

    /**
     * 创建基础测试数据
     */
    private List<TestBizEntity> createTestEntities() {
        List<TestBizEntity> entities = new ArrayList<>();
        
        // 测试数据1
        TestBizEntity entity1 = new TestBizEntity();
        entity1.setBizName("演示订单管理");
        entity1.setBizCode("DEMO_ORDER_001");
        entity1.setBizType(1);
        entity1.setStatus(1);
        entity1.setDescription("这是一个演示订单管理业务");
        entities.add(entity1);
        
        // 测试数据2
        TestBizEntity entity2 = new TestBizEntity();
        entity2.setBizName("演示用户管理");
        entity2.setBizCode("DEMO_USER_001");
        entity2.setBizType(1);
        entity2.setStatus(0);
        entity2.setDescription("这是一个演示用户管理业务");
        entities.add(entity2);
        
        // 测试数据3
        TestBizEntity entity3 = new TestBizEntity();
        entity3.setBizName("演示支付管理");
        entity3.setBizCode("DEMO_PAYMENT_001");
        entity3.setBizType(2);
        entity3.setStatus(1);
        entity3.setDescription("这是一个演示支付管理业务");
        entities.add(entity3);
        
        return entities;
    }

    /**
     * 创建更多测试数据
     */
    private List<TestBizEntity> createMoreTestEntities() {
        List<TestBizEntity> entities = new ArrayList<>();
        
        // 库存管理
        TestBizEntity entity1 = new TestBizEntity();
        entity1.setBizName("演示库存管理");
        entity1.setBizCode("DEMO_INVENTORY_001");
        entity1.setBizType(2);
        entity1.setStatus(1);
        entity1.setDescription("这是一个演示库存管理业务");
        entities.add(entity1);
        
        // 报表管理
        TestBizEntity entity2 = new TestBizEntity();
        entity2.setBizName("演示报表管理");
        entity2.setBizCode("DEMO_REPORT_001");
        entity2.setBizType(3);
        entity2.setStatus(1);
        entity2.setDescription("这是一个演示报表管理业务");
        entities.add(entity2);
        
        // 系统配置
        TestBizEntity entity3 = new TestBizEntity();
        entity3.setBizName("演示系统配置");
        entity3.setBizCode("DEMO_CONFIG_001");
        entity3.setBizType(3);
        entity3.setStatus(0);
        entity3.setDescription("这是一个演示系统配置业务");
        entities.add(entity3);
        
        return entities;
    }
} 